package com.yaozheng.vocationaltraining.fragment.userinfo;

import android.content.Context;
import android.text.InputType;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.yaozheng.vocationaltraining.R;
import com.yaozheng.vocationaltraining.fragment.BaseFragment;
import com.yaozheng.vocationaltraining.iview.userinfo.IUpdateUserInfoView;
import com.yaozheng.vocationaltraining.service.impl.userinfo.UpdateUserInfoServiceImpl;
import com.yaozheng.vocationaltraining.service.userinfo.UpdateUserInfoService;
import com.yaozheng.vocationaltraining.utils.Constants;
import com.yaozheng.vocationaltraining.utils.ErrorUtils;
import com.yaozheng.vocationaltraining.utils.LogUtils;
import com.yaozheng.vocationaltraining.utils.TypeUtils;
import com.yaozheng.vocationaltraining.utils.ViewUtils;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.androidannotations.annotations.AfterViews;
import org.androidannotations.annotations.Bean;
import org.androidannotations.annotations.Click;
import org.androidannotations.annotations.EFragment;
import org.androidannotations.annotations.UiThread;
import org.androidannotations.annotations.ViewById;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 修改资料
 */
@EFragment(R.layout.activity_update_data)
public class UpdateUserInfoFragment extends BaseFragment implements IUpdateUserInfoView {
    @ViewById
    ImageView headRightImage;
    @ViewById
    TextView headTitleText, headRightText;
    String title;
    String value;
    int position;
    JSONObject itemData;
    JSONArray currUserInfoJsonArray;
    @ViewById
    EditText updateDataContentEdit;
    @Bean(UpdateUserInfoServiceImpl.class)
    UpdateUserInfoService updateUserInfoService;
    InputMethodManager imm;


    @AfterViews
    public void initView() {

//        headRightImage.setImageResource(R.drawable.save_button_image_ioc);
        itemData = TypeUtils.getJsonObject(currUserInfoJsonArray, position);
        int inputType = TypeUtils.getJsonInteger(itemData, "inputType", -1);
        if (inputType == -1) {
            updateDataContentEdit.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_NORMAL);
        } else {
            updateDataContentEdit.setInputType(inputType);
        }
        headTitleText.setText(title);

//        headRightText.setVisibility(View.VISIBLE);
//        headRightText.setText("确定");
        updateUserInfoService.init(this);
        headRightText.setTextColor(getResources().getColor(R.color.leran_list_type_item_selected_font_color));
        headRightText.setText("提交");
        headRightImage.setVisibility(View.GONE);
        headRightText.setVisibility(View.VISIBLE);

//        if (value != null && !"".equals(value)) {
//            updateDataContentEdit.setText(value);
//            try {
//                updateDataContentEdit.setSelection(value.length());
//            } catch (Exception e) {
//                ErrorUtils.outErrorLog(e);
//            }
//        }
        updateDataContentEdit.setText(value);
        ViewUtils.editCursorLast(updateDataContentEdit);
        updateDataContentEdit.requestFocus();
        imm = (InputMethodManager) getBaseActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.showSoftInput(updateDataContentEdit, InputMethodManager.RESULT_SHOWN);
        imm.toggleSoftInput(InputMethodManager.SHOW_FORCED, InputMethodManager.HIDE_IMPLICIT_ONLY);


    }


    public void setTitle(String title) {
        this.title = title;
    }

    public void setValue(String value) {
        this.value = value;
    }


    public void setCurrUserInfoJsonArray(JSONArray currUserInfoJsonArray) {
        this.currUserInfoJsonArray = currUserInfoJsonArray;
    }

    public void setPosition(int position) {
        this.position = position;
    }

    /**
     * 保存点击
     */
    @Click(R.id.headRightText)
    public void headRightClick() {
        String updateDataContentEditValue = updateDataContentEdit.getText()
                .toString();

        String errorMessage = TypeUtils.getJsonString(itemData, "errorMessage");
        String regularExpressions = TypeUtils.getJsonString(itemData, "regularExpressions");
        if (regularExpressions != null && !"".equals(regularExpressions) && errorMessage != null && !"".equals(errorMessage)) {
            Pattern pattern = Pattern.compile(regularExpressions);

            Matcher matcher = pattern.matcher(updateDataContentEditValue);
            if (!matcher.matches()) {
                alertMessage(errorMessage);
                return;
            }
        }

        if (!"".equals(updateDataContentEditValue) && value != null && !value.equals(updateDataContentEditValue)) {
//            setIntentString("newValue", updateDataContentEditValue);
//            setResult(Constants.UPDATE_USER_INFO_RESULT_CODE, getIntent());
//            updateUserInfoService.updateUserInfo();

            showOperatingProgressDialog("修改中");
            itemData.put("value", updateDataContentEditValue);
            updateUserInfoService.updateUserInfo(currUserInfoJsonArray);

        } else {
            getBaseActivity().backClick();
        }
    }

    @UiThread
    @Override
    public void updateUserInfoSuccess(JSONObject jsonObject) {
        cancelOperatingProgressDialog();
        boolean resultBoolean = TypeUtils.getJsonBoolean(
                TypeUtils.getJsonObject(jsonObject, "data"), "result");
        if (resultBoolean) {
            alertMessage("修改成功");
            getBaseActivity().backClick();
        } else {
            alertMessage("修改失败");
        }

    }

    @UiThread
    @Override
    public void updateUserInfoError(String error) {
        cancelOperatingProgressDialog();
        alertMessage(error);

    }

    @Override
    public boolean backPressed() {
        imm.hideSoftInputFromWindow(updateDataContentEdit.getWindowToken(), 0);
        return super.backPressed();
    }

    @Override
    public void onDestroyView() {
        imm.hideSoftInputFromWindow(updateDataContentEdit.getWindowToken(), 0);
        title = null;
        value = null;
        position = -1;
        itemData = null;
        currUserInfoJsonArray = null;
        super.onDestroyView();
    }
}